package app.modules 
{
	import app.AppModel;
	import events.TreeEvents;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import gui.buttons.RadioButton;
	import gui.tree.NodeFolder;
	import gui.tree.NodeRB;
	import gui.tree.TreeFoldersView;
	import utils.ErrorsCollector;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class ModuleChoseFurniture extends Sprite
	{
		private var _model:AppModel;
		private var _folders:Vector.<TreeFolderInfo>;
		
		private var _tree:TreeFoldersView;
		private var _currentPreview:DisplayObject = null;
		private var _moduleChooseAttrib:ModuleChooseAttrib;
		private var _currentFolder:NodeFolder = null;
		
		public function ModuleChoseFurniture(model:AppModel, folders:Vector.<TreeFolderInfo>, title:String = "") 
		{
			_model = model;
			_folders = folders;
			addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
		}
		
		private function handleAddedToStage(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
			initModule();
		}
		
		private function initModule():void 
		{
			_tree = new TreeFoldersView("");
			addChild(_tree);
			
			for each(var treeFolderInfo:TreeFolderInfo in _folders)
			{
				var nodeFolder:NodeFolder = new NodeFolder(treeFolderInfo.title, treeFolderInfo.header);
				
				for each(var chooseAttribInfo:ChooseAttribModel in treeFolderInfo.nodes)
				{
					nodeFolder.addItem(new NodeRB(chooseAttribInfo.titleRB, chooseAttribInfo));
				}
				_tree.addFolder(nodeFolder);
			}
			_tree.updateView();
			_tree.addEventListener(TreeEvents.ITEM_SELECTED, handleItemSelected);
			_tree.addEventListener(TreeEvents.FOLDER_SELECTED, handleFolderSelected);
			_tree.foldersRB[0].selected = true;
		}
		
		private function handleFolderSelected(e:TreeEvents):void 
		{
			_currentFolder = _tree.getSelectedFolder();
		}
		
		private function handleItemSelected(e:TreeEvents):void 
		{
			var item: NodeRB = _tree.getSelectedRB();
			if (item != null)
			{
				var chooseAttribModel:ChooseAttribModel = item.value as ChooseAttribModel;
				if (_moduleChooseAttrib != null)
				{
					if (_moduleChooseAttrib.parent != null)
					{
						_moduleChooseAttrib.parent.removeChild(_moduleChooseAttrib);
					}
				}
				if (chooseAttribModel != null)
				{
					var header:String = "";
					if (_currentFolder != null)
					{
						header = _currentFolder.extendedTitle;
					}
					_moduleChooseAttrib = new ModuleChooseAttrib(_model,  chooseAttribModel, header);
					addChild(_moduleChooseAttrib);
				}else
				{
					handleError("chooseAttribModel is null");
				}
				
			}else
			{
				handleError("item selected null");
			}
		}
		
		private function handleError(err:String):void 
		{
			ErrorsCollector.getInstance().collectError("Module Choose furn: " + err);
		}
		
	}

}